<template>
  <div class="sampling-tasks">
    <!-- 顶部导航 -->
    <van-nav-bar
      :title="`${selectedStorage?.name} - 取样任务`"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="$router.go(-1)"
    >
      <template #right>
        <van-icon name="filter" size="18" @click="showFilter = true" />
      </template>
    </van-nav-bar>

    <!-- 冷库基本信息 -->
    <div class="storage-info-card">
      <div class="storage-header">
        <div class="storage-name">
          <van-tag type="primary" size="medium">{{ selectedStorage?.group }}</van-tag>
          <h3>{{ selectedStorage?.name }}</h3>
        </div>
        <div class="location-btn">
          <van-button
            round
            size="small"
            icon="location"
            type="primary"
            plain
            @click="showMap(selectedStorage!)"
          >
            查看位置
          </van-button>
        </div>
      </div>

      <div class="storage-details">
        <div class="info-row">
          <label>地址:</label>
          <span>{{ selectedStorage?.address }}</span>
        </div>
        <div class="info-row">
          <label>坐标:</label>
          <span>纬度: {{ selectedStorage?.latitude }}, 经度: {{ selectedStorage?.longitude }}</span>
        </div>
        <div class="info-row">
          <label>容量:</label>
          <span>{{ selectedStorage?.capacity }}m³ </span>
        </div>
      </div>
    </div>

    <!-- 任务过滤 -->
    <div class="filter-section">
      <div class="filter-tabs">
        <van-tabs v-model:active="activeFilter" @change="filterTasks" shrink swipeable>
          <van-tab title="全部" />
          <van-tab title="待取样" />
          <van-tab title="进行中" />
          <van-tab title="已完成" />
          <van-tab title="已延迟" />
        </van-tabs>
      </div>
    </div>

    <!-- 任务列表 -->
    <div class="tasks-list">
      <!-- 空状态 -->
      <div v-if="filteredTasks.length === 0" class="empty-status">
        <van-empty image="search" description="没有符合条件的取样任务">
          <van-button round type="primary" class="reset-btn" @click="resetFilter">
            重置筛选条件
          </van-button>
        </van-empty>
      </div>

      <!-- 任务列表 -->
      <van-list v-else>
        <van-cell class="list-header">
          <template #title>
            <span>共 {{ filteredTasks.length }} 个任务</span>
          </template>
          <template #value>
            <van-button size="small" type="primary" @click="addTask">新建任务</van-button>
          </template>
        </van-cell>

        <div v-for="task in filteredTasks" :key="task.id" class="task-card">
          <van-swipe-cell>
            <!-- 任务卡片内容 -->
            <div class="task-content">
              <div class="task-header">
                <div class="task-id">#{{ task.orderNumber }}</div>
                <div class="task-status">
                  <van-tag :type="getStatusTagType(task.status)" size="medium">
                    {{ getStatusText(task.status) }}
                  </van-tag>
                </div>
              </div>

              <div class="task-details">
                <div class="detail-row">
                  <label>冷库仓号:</label>
                  <span>{{ task.roomNumber }}</span>
                </div>
                <div class="detail-row">
                  <label>计划取样时间:</label>
                  <span>{{ formatDateTime(task.scheduledTime) }}</span>
                </div>
                <div class="detail-row">
                  <label>取样员:</label>
                  <span>{{ task.sampler }}</span>
                </div>
                <div class="detail-row">
                  <label>预计耗时:</label>
                  <span>{{ task.estimatedDuration }}分钟</span>
                </div>
                <div class="detail-row">
                  <label>样本信息:</label>
                  <span>{{ task.sampleType }} x {{ task.sampleQuantity }}</span>
                </div>
                <div class="detail-row">
                  <label>金额:</label>
                  <span class="task-amount">¥{{ task.amount.toFixed(2) }}</span>
                </div>
              </div>

              <div v-if="task.notes" class="task-notes">
                <van-icon name="notes" size="14px" color="#969799" />
                <span>{{ task.notes }}</span>
              </div>

              <div class="task-actions">
                <van-button
                  v-if="task.status === 'pending' || task.status === 'delayed'"
                  round
                  size="small"
                  type="primary"
                  @click="startTask(task)"
                >
                  开始取样
                </van-button>
                <van-button
                  v-else-if="task.status === 'inProgress'"
                  round
                  size="small"
                  type="primary"
                  @click="completeTask(task)"
                >
                  完成取样
                </van-button>
                <van-button round size="small" plain @click="viewTaskDetail(task)">
                  查看详情
                </van-button>
              </div>
            </div>

            <!-- 右滑操作 -->
            <template #right>
              <van-button
                square
                type="danger"
                text="删除"
                class="delete-button"
                @click="deleteTask(task.id)"
              />
            </template>
          </van-swipe-cell>
        </div>
      </van-list>
    </div>

    <!-- 添加任务按钮 -->
    <div class="fixed-footer">
      <van-button round type="primary" block @click="addTask"> 添加取样任务 </van-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast, Dialog } from 'vant'
import dayjs from 'dayjs'
import type { ColdStorage, SamplingTask, SamplingTaskStatus } from '../types/task'

export default defineComponent({
  name: 'SamplingTasks',
  setup() {
    const router = useRouter()
    const route = useRoute()

    // 数据状态
    const selectedStorage = ref<ColdStorage | null>(null)
    const tasks = ref<SamplingTask[]>([])
    const showFilter = ref(false)
    const activeFilter = ref(0)
    const showMapPopup = ref(false)

    // 状态过滤器对应关系
    const filterMap: { [key: number]: SamplingTaskStatus | 'all' } = {
      0: 'all',
      1: 'pending',
      2: 'inProgress',
      3: 'completed',
      4: 'delayed',
    }

    // 获取状态文本
    const getStatusText = (status: SamplingTaskStatus): string => {
      const statusMap: Record<SamplingTaskStatus, string> = {
        pending: '待取样',
        inProgress: '进行中',
        completed: '已完成',
        delayed: '已延迟',
      }
      return statusMap[status] || status
    }

    // 获取状态标签类型
    const getStatusTagType = (status: SamplingTaskStatus) => {
      const typeMap: Record<SamplingTaskStatus, string> = {
        pending: 'primary',
        inProgress: 'warning',
        completed: 'success',
        delayed: 'danger',
      }
      return typeMap[status] || 'default'
    }

    // 格式化日期时间
    const formatDateTime = (date: Date): string => {
      return dayjs(date).format('YYYY-MM-DD HH:mm')
    }

    // 查看地图
    const showMap = (storage: ColdStorage) => {
      showMapPopup.value = true
    }

    // 开始任务
    const startTask = (task: SamplingTask) => {
      task.status = 'inProgress'
      Toast('任务已开始')
    }

    // 完成任务
    const completeTask = (task: SamplingTask) => {
      task.status = 'completed'
      task.actualDuration = Math.floor(task.estimatedDuration * (0.9 + Math.random() * 0.2))
      Toast('任务已完成')
    }

    // 查看任务详情
    const viewTaskDetail = (task: SamplingTask) => {
      // 实际项目中应导航到任务详情页面
      Toast(`查看任务 ${task.orderNumber}`)
    }

    // 添加任务
    const addTask = () => {
      const newTask: SamplingTask = {
        id: `t${tasks.value.length + 1}`,
        orderNumber: `ORD${dayjs().format('YYYYMMDD')}${100 + tasks.value.length + 1}`,
        coldStorageId: selectedStorage.value!.id,
        coldStorageName: selectedStorage.value!.name,
        roomNumber: `R-${Math.floor(Math.random() * 100)}`,
        sampler: '取样员' + (Math.floor(Math.random() * 10) + 1),
        scheduledTime: new Date(Date.now() + Math.floor(Math.random() * 7) * 24 * 3600 * 1000),
        status: 'pending',
        estimatedDuration: Math.floor(Math.random() * 120) + 30,
        sampleType: ['血液', '细胞', '组织', '血清'][Math.floor(Math.random() * 4)],
        sampleQuantity: Math.floor(Math.random() * 20) + 1,
        amount: Math.random() * 5000 + 500,
        notes: Math.random() > 0.7 ? '特殊处理要求：低温运输' : undefined,
      }

      tasks.value.unshift(newTask)
      Toast('新任务已添加')
    }

    // 删除任务
    const deleteTask = (id: string) => {
      Dialog({
        title: '删除任务',
        message: '确定要删除这个取样任务吗？此操作不可撤销。',
      }).then(() => {
        const index = tasks.value.findIndex((t) => t.id === id)
        if (index !== -1) {
          tasks.value.splice(index, 1)
          Toast('任务已删除')
        }
      })
    }

    // 过滤任务
    const filterTasks = () => {
      // 实现滚动到顶部效果
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }

    // 重置过滤
    const resetFilter = () => {
      activeFilter.value = 0
    }

    // 计算属性
    const filteredTasks = computed(() => {
      if (!selectedStorage.value) return []

      const statusFilter = filterMap[activeFilter.value]

      return tasks.value
        .filter((task) => {
          const matchesStorage = task.coldStorageId === selectedStorage.value!.id
          const matchesStatus = statusFilter === 'all' || task.status === statusFilter

          return matchesStorage && matchesStatus
        })
        .sort((a, b) => {
          // 待处理任务优先
          if (a.status === 'pending' && b.status !== 'pending') return -1
          if (a.status !== 'pending' && b.status === 'pending') return 1

          // 再进行中任务
          if (a.status === 'inProgress' && b.status !== 'inProgress') return -1
          if (a.status !== 'inProgress' && b.status === 'inProgress') return 1

          // 最后按时间排序
          return b.scheduledTime.getTime() - a.scheduledTime.getTime()
        })
    })

    // 模拟数据
    const initData = () => {
      const storageId = route.query.id as string

      // 模拟冷库数据
      const mockStorages: ColdStorage[] = [
        {
          id: 'cs1',
          name: '华南冷链中心',
          group: '华南区',
          address: '广东省广州市黄埔区科学城开源大道188号',
          latitude: 23.1832,
          longitude: 113.511,
          capacity: 12000,
          currentUsage: 9500,
          tasksCount: 8,
        },
        {
          id: 'cs2',
          name: '华东冷藏基地',
          group: '华东区',
          address: '上海市浦东新区张江高科园区创新路99号',
          latitude: 31.2134,
          longitude: 121.539,
          capacity: 18000,
          currentUsage: 11500,
          tasksCount: 12,
        },
        {
          id: 'cs3',
          name: '华北冷藏中心',
          group: '华北区',
          address: '北京市海淀区上地科技园区8号',
          latitude: 39.9931,
          longitude: 116.321,
          capacity: 9000,
          currentUsage: 7000,
          tasksCount: 5,
        },
        {
          id: 'cs4',
          name: '西南冷冻仓库',
          group: '西南区',
          address: '四川省成都市高新区天府软件园C区8号楼',
          latitude: 30.5482,
          longitude: 104.067,
          capacity: 15000,
          currentUsage: 11000,
          tasksCount: 15,
        },
        {
          id: 'cs5',
          name: '华南冷冻基地',
          group: '华南区',
          address: '广东省深圳市南山区科技园北区6号楼',
          latitude: 22.5521,
          longitude: 113.949,
          capacity: 11000,
          currentUsage: 8500,
          tasksCount: 7,
        },
        {
          id: 'cs6',
          name: '华东冷链枢纽',
          group: '华东区',
          address: '浙江省杭州市余杭区未来科技城88号',
          latitude: 30.2898,
          longitude: 120.006,
          capacity: 22000,
          currentUsage: 14500,
          tasksCount: 18,
        },
      ]

      selectedStorage.value = mockStorages.find((s) => s.id === storageId) || null

      // 生成模拟任务数据
      const statuses: SamplingTaskStatus[] = ['pending', 'inProgress', 'completed', 'delayed']
      tasks.value = []

      if (selectedStorage.value) {
        for (let i = 0; i < selectedStorage.value.tasksCount; i++) {
          tasks.value.push({
            id: `t${i + 1}`,
            orderNumber: `ORD${dayjs().format('YYYYMMDD')}${100 + i + 1}`,
            coldStorageId: selectedStorage.value.id,
            coldStorageName: selectedStorage.value.name,
            roomNumber: `R-${Math.floor(Math.random() * 100)}`,
            sampler: '取样员' + (Math.floor(Math.random() * 10) + 1),
            scheduledTime: new Date(Date.now() + Math.floor(Math.random() * 7) * 24 * 3600 * 1000),
            status: statuses[i % 4],
            estimatedDuration: Math.floor(Math.random() * 120) + 30,
            actualDuration: i < 5 ? Math.floor(Math.random() * 60) + 30 : undefined,
            sampleType: ['血液', '细胞', '组织', '血清'][Math.floor(Math.random() * 4)],
            sampleQuantity: Math.floor(Math.random() * 20) + 1,
            amount: Math.random() * 5000 + 500,
            notes: Math.random() > 0.7 ? '特殊处理要求：低温运输' : undefined,
          })
        }
      }
    }

    // 生命周期
    onMounted(() => {
      initData()
    })

    return {
      selectedStorage,
      tasks,
      showFilter,
      activeFilter,
      showMapPopup,
      filteredTasks,
      getStatusText,
      getStatusTagType,
      formatDateTime,
      showMap,
      startTask,
      completeTask,
      viewTaskDetail,
      addTask,
      deleteTask,
      filterTasks,
      resetFilter,
    }
  },
})
</script>

<style lang="scss" scoped>
.sampling-tasks {
  padding-bottom: 60px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .storage-info-card {
    background: white;
    margin: 12px;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    .storage-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f7f8fa;

      .storage-name {
        h3 {
          margin: 0;
          font-size: 18px;
          color: #333;
        }

        .van-tag {
          margin-top: 4px;
          margin-right: 8px;
        }
      }
    }

    .storage-details {
      .info-row {
        display: flex;
        margin-bottom: 12px;
        font-size: 14px;

        label {
          width: 60px;
          color: #969799;
          flex-shrink: 0;
        }

        span {
          color: #333;
          flex: 1;
        }
      }
    }
  }

  .filter-section {
    background: white;
    padding: 0 12px;
    margin-top: -4px;
    position: sticky;
    top: 46px; // 导航栏高度
    z-index: 99;

    .filter-tabs {
      :deep(.van-tabs__line) {
        background: #1989fa;
      }

      :deep(.van-tab) {
        padding: 0 10px;
      }
    }
  }

  .tasks-list {
    padding: 0 12px;

    .list-header {
      background-color: #f0f7ff;
      border-radius: 8px 8px 0 0;
      margin-top: 12px;
      font-weight: bold;
    }

    .empty-status {
      margin-top: 40px;

      .reset-btn {
        margin-top: 16px;
      }
    }

    .task-card {
      margin-bottom: 12px;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

      .task-content {
        background: white;
        padding: 16px;

        .task-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;
          padding-bottom: 12px;
          border-bottom: 1px solid #f7f8fa;

          .task-id {
            font-weight: bold;
            color: #1989fa;
            font-size: 16px;
          }
        }

        .task-details {
          .detail-row {
            display: flex;
            margin-bottom: 10px;
            font-size: 14px;

            label {
              width: 100px;
              color: #969799;
              flex-shrink: 0;
            }

            span {
              color: #333;
              flex: 1;

              &.task-amount {
                color: #ee0a24;
                font-weight: bold;
              }
            }
          }
        }

        .task-notes {
          margin-top: 12px;
          padding: 10px;
          background: #fff8e1;
          border-radius: 4px;
          display: flex;
          font-size: 13px;
          color: #666;

          .van-icon {
            flex-shrink: 0;
            margin-right: 8px;
            margin-top: 2px;
          }
        }

        .task-actions {
          display: flex;
          justify-content: flex-end;
          margin-top: 16px;
          gap: 8px;

          .van-button {
            flex: 0 1 auto;
            min-width: 100px;
          }
        }
      }

      .delete-button {
        height: 100%;
      }
    }
  }

  .fixed-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 16px;
    background: white;
    border-top: 1px solid #f7f8fa;

    .van-button {
      font-weight: bold;
      font-size: 16px;
    }
  }
}
</style>
